package client.view;

import client.dao.MessageDao;
import client.dao.UserDao;
import client.pojo.Message;
import client.pojo.User;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import javax.swing.*;
import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 聊天窗口
 */
public class ChatView extends Application {
    private TextArea activeUserText;
    private TextArea messageText;
    private TextField inputMessage;
    private ObjectInputStream inputStream;
    private ObjectOutputStream outputStream;
    private Socket socket;
    private String yourInputName;
    private String serverAddress;
    private int port;
    private MessageDao messageDao;

    public ChatView(String yourInputName, String serverAddress, int port, Socket socket, ObjectOutputStream outputStream,ObjectInputStream inputStream) {
        this.yourInputName = yourInputName;
        this.serverAddress = serverAddress;
        this.port = port;
        this.socket = socket;
        this.outputStream = outputStream;
        this.inputStream = inputStream;
    }

    public TextArea getActiveUserText() {
        return activeUserText;
    }

    public void setActiveUserText(TextArea activeUserText) {
        this.activeUserText = activeUserText;
    }

    public TextArea getMessageText() {
        return messageText;
    }

    public void setMessageText(TextArea messageText) {
        this.messageText = messageText;
    }

    public TextField getInputMessage() {
        return inputMessage;
    }

    public void setInputMessage(TextField inputMessage) {
        this.inputMessage = inputMessage;
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle(yourInputName + "                                                                 " +
                "Le Chat - chatting");
        // 新建一个GirdPane
        GridPane grid = new GridPane();
        grid.setHgap(5);
        grid.setVgap(5);
        grid.setPadding(new Insets(10, 10, 10, 10));
        messageText = new TextArea("Welcome to Le Chat!\nPlease type in your message and press send\n");
        messageText.setScrollTop(Double.MAX_VALUE);
        messageText.setStyle("-fx-font-size: 15px;px-fx-font-family: monospace;");
        messageText.setEditable(false);
        messageText.setMinWidth(490);
        messageText.setMinHeight(310);
        grid.add(messageText, 0, 0);
        activeUserText = new TextArea("Active users:\n");
        activeUserText.setEditable(false);
        activeUserText.setStyle("-fx-font-size: 15px;px-fx-font-family: monospace;");
        activeUserText.setMinWidth(100);
        activeUserText.setMinHeight(310);
        grid.add(activeUserText, 1, 0);
        inputMessage = new TextField();
        inputMessage.setPromptText("Please type in your message and press send" + '\n');
        inputMessage.setMinWidth(490);
        inputMessage.setMinHeight(30);
        grid.add(inputMessage, 0, 1);
        Button sendButton = new Button("Send");
        sendButton.setMinHeight(30);
        sendButton.setMinWidth(170);
        sendButton.setStyle("-fx-background-color: #50b4ea;-fx-font-size: 14");
        grid.add(sendButton, 1, 1);
        Scene scene = new Scene(grid, 689, 387);
        primaryStage.setScene(scene);
        /**
         * 关闭窗口的操作
         */
        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                try {
                    System.out.println("窗口关闭，当前用户已下线");
                    outputStream.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        new Thread(() -> {
            try {
                while (true) {
                    Message message = (Message) inputStream.readObject();
                    if (message != null) {
                        if (message.getType() == 0) {
                            //正常消息
                            messageText.appendText(message.getUserName() + "(" + message.getSendTime() + ")" + "\n" + message.getContent() + "\n\n");
                        } else if(message.getType() == 1){
                            //加入用户
                            activeUserText.setText("Active users:\n" + message.getContent());
                        }else {
                            messageText.appendText(message.getContent());
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println(yourInputName + "已下线");
                Platform.runLater(()->{
                    primaryStage.close();
                });
            }
        }).start();

        //发送消息
        sendButton.setOnAction(e -> {
            try {
                if (inputMessage.getText() != "") {
                    Message message = new Message(yourInputName, inputMessage.getText(), new SimpleDateFormat("yyyy-MM- dd HH:mm:ss").format(new Date())+"", 0);
                    outputStream.writeObject(message);
                    outputStream.flush();
                    inputMessage.setText("");
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        });
        primaryStage.getIcons().add(new Image("client/view/icon.png", 256, 256, true, true));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}
